package com.mlk.core.config;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.Data;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * Swqgger 配置
 *
 * @author trekxu
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    // 定义分隔符
    private static final String splitor = ";";

    /**
     * Swagger 属性配置类
     */
    @ConfigurationProperties("swagger.config")
    @Configuration
    @Data
    private static class SwaggerProperty {

        private boolean enableSwagger = true;

        private String basePackage;

        private String title = "Swagger-API";

        private String description = StringUtils.EMPTY;

        private String version = "1.0.0";
    }


    @Bean
    public Docket createRestApi(SwaggerProperty swaggerProperty) {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo(swaggerProperty))
                // 是否开启
                .enable(swaggerProperty.enableSwagger).select()
                // 扫描的路径包
                .apis(RequestHandlerSelectors.basePackage(swaggerProperty.basePackage))
                // 指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any()).build().pathMapping("/");
    }

    private ApiInfo apiInfo(SwaggerProperty swaggerProperty) {
        return new ApiInfoBuilder()
                .title(swaggerProperty.title) // 标题
                .description(swaggerProperty.description) // 描述
                .version(swaggerProperty.version) // 版本号
                .build();
    }

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }


}
